import java.util.ArrayList;
import java.util.Arrays;

public class MyArrayList implements Ilist{
    public int[] elem;
    public int usedSize;
    public static final int DEFAULT_CAPACITY = 5;
    public MyArrayList() {
        elem = new int[DEFAULT_CAPACITY];

    }

    @Override
    public boolean isFull() {
        return usedSize == elem.length;
    }

    @Override//再线性表中存储一个数据，默认存到末尾
    public void add(int data) {
        if (isFull()) {
            //满了，对数组进行扩容
            grow();
        }
        elem[usedSize++] = data;

    }
    //扩容方法
    private void grow(){
        elem = Arrays.copyOf(elem,2*elem.length);
        //默认二倍扩容
    }

    //自定义几倍扩容
    private void grow(int growNum){
        elem = Arrays.copyOf(elem,growNum*elem.length);
    }

    @Override//在指定位置进行插入
    public void add(int pos, int data) {
        checkPos(pos);
        if (isFull()){
            //满了，进行数组扩容
            grow();
        }
        for (int i = usedSize - 1; i >= pos ; i--) {
            elem[i + 1] = elem[i];
        }
        elem[pos] = data;
        usedSize++;


    }
    public void checkPos(int pos){
        if(pos < 0 || pos > usedSize){
            throw new PosOutOfBoundsException("添加元素时pos位置不合法" + pos);
        }
    }
    public void checkPosByGet(int pos){
        if(pos < 0 || pos >= usedSize){
            throw new PosOutOfBoundsException("获取元素时pos位置不合法" );
        }
    }

    @Override
    public boolean contains(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if (elem[i] == toFind ) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if (elem[i] == toFind ) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        checkPosByGet(pos);
        if (isEmpty()){
            throw new ListEmptyException("获取元素时顺序表为空");
        }
        return elem[pos];

    }

    @Override
    public boolean isEmpty() {
        return usedSize == 0;
    }

    @Override
    public void set(int pos, int value) {

    }

    @Override
    //删除数据
    public void remove(int toRemove) {
        int index = indexOf(toRemove);
        if (index == -1) {
            System.out.println("没有你要删除的数据");
        }
        for (int i = index; i < usedSize - 1 ; i++) {
                elem[index] = elem[index + 1];
        }


    }

    @Override
    public int size() {
        return usedSize;
    }

    @Override
    public void clear() {
        usedSize = 0;

    }

    @Override
    public void display() {
        for (int i = 0; i < usedSize; i++) {
            System.out.print(elem[i] + " ");
        }
        System.out.println();
    }
}
